﻿using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore;
using YDT_UserService.Domain.Entities;

namespace YDT_UserService.Infrastructure.Data
{
    public class UserServiceDbContext : DbContext
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public UserServiceDbContext(DbContextOptions<UserServiceDbContext> options) : base(options) { }

        /// <summary>用户表</summary>
        public DbSet<User> Users { get; set; }

        /// <summary>
        /// 配置模型 - 定义数据库表结构和关系
        /// </summary>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // 配置用户实体
            modelBuilder.Entity<User>(entity =>
            {
                // 主键配置
                entity.HasKey(e => e.Id);

                // 属性配置
                entity.Property(e => e.UserName)
                    .IsRequired()
                    .HasMaxLength(50); // 用户名最大长度50

                entity.Property(e => e.PasswordHash)
                    .IsRequired()
                    .HasMaxLength(255); // 密码哈希长度

                entity.Property(e => e.UserNickname)
                    .IsRequired()
                    .HasMaxLength(20); // 用户昵称最大长度20

                entity.Property(e => e.UserQQ)
                    .HasMaxLength(15); // QQ号最大长度15

                entity.Property(e => e.UserPhone)
                    .IsRequired()
                    .HasMaxLength(11); // 手机号长度11

                entity.Property(e => e.Status)
                    .HasConversion<string>() // 枚举转换为字符串存储
                    .HasMaxLength(20);

                // 索引配置
                entity.HasIndex(e => e.UserName)
                    .IsUnique(); // 用户名唯一索引

                entity.HasIndex(e => e.UserPhone)
                    .IsUnique(); // 手机号唯一索引

                entity.HasIndex(e => e.Status); // 状态索引
                entity.HasIndex(e => e.CreateTime); // 创建时间索引
            });
        }

        /// <summary>
        /// 保存更改 - 自动设置更新时间
        /// </summary>
        public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            // 自动设置更新时间
            var entries = ChangeTracker.Entries()
                .Where(e => e.Entity is User &&
                           (e.State == EntityState.Modified || e.State == EntityState.Added));

            foreach (var entityEntry in entries)
            {
                ((User)entityEntry.Entity).UpdateTime = DateTime.UtcNow;
            }

            return await base.SaveChangesAsync(cancellationToken);
        }
    }
}
